package cur.nature.component.quartz;

import cur.nature.component.quartz.service.Component_QuartzService;
import cur.nature.framework.core.log.LOG;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
@ConditionalOnProperty( value = {"cur.component.quartz.enable"})
public class QuartzListener {
    @Autowired
    private Component_QuartzService schedulerService;
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    @Bean
    public ApplicationListener onQuartzStart() {
        return (ApplicationListener<ApplicationReadyEvent>) event -> {
                try {
                    LOG.info("初始化quartz调度器.........");
                    schedulerFactoryBean.start();
                    schedulerService.refresh();
                } catch (Exception ex) {
                    LOG.error("初始化quartz调度器异常: ", ex);
                }
                LOG.info("Quartz started-------------------------------");
            };
    };

    @Bean
    public ApplicationListener onQuartzStop() {
        return (ApplicationListener<ContextClosedEvent>) event -> {
            schedulerFactoryBean.stop();
            LOG.info("Quartz stopped-------------------------------");
        };
    }

}
